'use strict';
var v='?=20171212';
var app = angular.module('myApp', [ 'ngRoute', 'tm.pagination','tm.headshow' ]);
app.config(function($controllerProvider, $compileProvider, $filterProvider,
		$provide, $routeProvider, $httpProvider) {
	app.register = {
		controller : $controllerProvider.register,
		directive : $compileProvider.directive,
		filter : $filterProvider.register,
		factory : $provide.factory,
		service : $provide.service
	};

	$routeProvider.when(
			'/:plugin/:page',
			{
				templateUrl : function(rd) {
					return 'pages/' + rd.plugin + '/' + rd.page + '.html'+v;
				},
				resolve : {
					load : function($q, $route, $rootScope) {
						var deferred = $q.defer();
						var dependencies = [ 'pages/'
								+ $route.current.params.plugin + '/'
								+ $route.current.params.page + '.js' ];
						$script(dependencies, function() {
							$rootScope.$apply(function() {
								deferred.resolve();
							});
						});
						return deferred.promise;
					}
				}
			}).when(
							'/:plugin/:page/:id',
							{
								templateUrl : function(rd) {
									return 'pages/' + rd.plugin + '/' + rd.page + '.html';
								},
								resolve : {
									load : function($q, $route, $rootScope) {

										var deferred = $q.defer();
										var dependencies = [ 'pages/'
												+ $route.current.params.plugin + '/'
												+ $route.current.params.page + '.js' ];
										$script(dependencies, function() {
											$rootScope.$apply(function() {
												deferred.resolve();
											});
										});
										return deferred.promise;
									}
								}
		}).otherwise({
								template : function(rd) {
									return '<div class="welcome" style="width:100%;background-color:#F8F8F8;">'+
				                	'<img src="images/welcome.png" width="579" height="191"></div>';
								}
		});

	// 注册拦截器
	$httpProvider.interceptors.push('httpInterceptor');
	$httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';

});

app.factory('httpInterceptor', [ '$q', '$injector','$window', function($q, $injector,$window) {
	var httpInterceptor = {
		'responseError' : function(response) {
			 if (response.status == 518) {
				angular.element(".loading").remove();
				
				alertMsg("提示","由于您长时间没有操作,会话已失效,请重新登录!",function(){	
					window.location= "/login.html";
				});
			 }else
				 return $q.reject(response);
		}
	};
	return httpInterceptor;
} ]);
app.factory('AppUtil',['$http', '$rootScope', '$window','$q', function($http, $rootScope, $window,$q) {
	return {
		LoadSessionUser : function() {
			$http.get("entity").success(function(response) {
				$rootScope.user = response.user;
			
				$rootScope.user.menu = response.menu;
				if($rootScope.user.superAdmin){
				 }
			}).error(function($window) {
				$window.location.href = "/login.html";
			});
		},
		loading : function(msg) {
			var message = "数据加载中，请稍后...";
			if(msg!=undefined)
				message = msg;
			if ($("body").hasClass("left-side-collapsed")){
				$(".nav-active").removeClass("nav-hover");
			}
			var template = '<div class="loading"><div class="msg">'
					+ '<img src="images/loading.gif">数据加载中，请稍后...</div>'
					+ '<div class="bg"></div></div>';
			angular.element("body .main-content").append(template);
			
		},
		remove_loading : function loading() {
			angular.element(".loading").remove();
			
		},
		
		ChangeMenu : function(path) {
			var current = angular.element("a[href='#" + path + "']");
			if(current.parents(".menu-list").size()==0)
				return;
			angular.element(".menu-list").removeClass("nav-active");
			angular.element(".sub-menu-list li").removeClass("active");
			$(".sub-menu-list li a.active").removeClass("active");
			current.parents(".menu-list").addClass("nav-active");
			
			if ($('body').hasClass('left-side-collapsed')){
					$(".sub-menu-list").hide();
					current.parents(".sub-menu-list").siblings("a.open_sub_menu").addClass("active");
					$(".open_sub_menu.active").siblings(".sub-menu-list").show();
					 
			}else{
					current.parents(".sub-menu-list").show().siblings("a.open_sub_menu").addClass("active");
			}
			current.addClass("active");
			setTimeout(function(){
				$(".select2").css("width",$(".select2").parent("div").width()+"px");
			},1000) 
		},
		GetLocalValue:function(key){
			return localStorage[key];
		},
		SetLocalValue:function(key,value){
			localStorage[key]=value;
		},
		Params : function(clazz){
			var params = {};
			angular.forEach(angular.element(clazz), function(data,index,array){
				if(data.value!=''){
					if(data.multiple==true){
						params[data.name]= $("#"+data.id).val().join(",");
					}else
						params[data.name]=data.value;
				}
			});
			return params;
		},
		Length:function(obj){
			var count= 0;
			for(var o in obj)
				count++;
			return count;
		},
		KeysAndNames:function(obj){
			var obj = {};
			var keys = [];
			var names = [];
			angular.forEach(angular.element('.table_store thead tr th'), function(data,index,array){
				var ele = angular.element(data);
				var column = ele.attr("column");
				if(ele.text()=='序号'||ele.text()=='明细'||column==null||column=='')return true;
				//隐藏列不进行导出
				if(!ele.hasClass("ng-hide")){
					keys.push(column);
					names.push(ele.text());
				}
			});
			obj.keys=keys;
			obj.names=names;
			return obj;
		},
		GetSearchOpt:function(){
			var search_opt = [];
			angular.element(".option_check_list span.active").each(function(i, n) {
				search_opt.push(table_th[$(n).attr("li_id")]);
			});
			return search_opt;
		},
		// 导出数据
		ExportData : function(postData) {
			var size = parseInt($(".page-total strong").text());
			if(size>65535){
				alertMsg("提示", "超过最大请求长度，请选择不超过65535条数据导出...");
				return;
			}
			var obj = this.KeysAndNames();// 获得表格列
			var search_opt = this.GetSearchOpt();// 获得筛选参数
			angular.element("#keys").val(JSON.stringify(obj.keys));
			angular.element("#names").val(JSON.stringify(obj.names));
			// 获得查询参数
			if(postData!=undefined){
				var params = postData.params;
				if (params!=undefined) {
					angular.element("#params").val(JSON.stringify(params));
				}
				var search_opt = postData.search_opt;
				if (search_opt!=undefined) {
					angular.element("#search_opt").val(JSON.stringify(search_opt));
				}
			}
//			alertMsg("提示", "正在导出数据,请稍后...");
			
			// 提交表单导出数据
			angular.element("#export_form").submit();
		},
		LoadGroups : function(){
			$rootScope.entity_brand_name='';
			$rootScope.entity_group_name='';
			$http.get("common/groups").success(function(data) {
				if(data.entitys.length==1){
					var user = $rootScope.user;
					if(user.authorityLevel=="3"){
						//单店，禁用事业部 entity_group_name
						var group = $("input[name='entity_group_name']");
						group.val(user.group_name);
						group.attr("disabled",true);
						//单店，禁用事业部 group_name
						var group = $("input[name='group_name']");
						group.val(user.group_name);
						group.attr("disabled",true);
						
						var brand = $("input[name='entity_brand_name']");
						brand.val(user.brand_name);
						brand.attr("disabled",true);
						
						var entity = $("input[name='entity_name']");
						entity.val(data.entitys[0].entity_name);
						entity.attr("disabled",true);
					}
					return;
				}
				$rootScope.map = data;
				$rootScope.groups = data.groups;
				$rootScope.gBrands = data.brands;
				$rootScope.entitys = data.entitys;
			});
		}
	}
}]);


app.controller('IndexCtrl', function($scope, $http, $rootScope, AppUtil,$routeParams ,$location) {
	
	$scope.$watch('entity_group_name', function(newValue,oldValue,scope){
		if(newValue==''){
			if($rootScope.map!=undefined){
				$rootScope.gBrands = $rootScope.map.brands;
				$rootScope.entitys = $rootScope.map.entitys;
				$rootScope.entity_brand_name='';
			}
		}
	});
	
	$scope.$watch('entity_brand_name', function(newValue,oldValue,scope){
		if(newValue==''){
			$("#entity_name").val("");
			if($rootScope.map!=undefined)
			$rootScope.entitys = $rootScope.map.entitys;
		}
	});
	
	//清除事业部
	$scope.clearGroup=function(){
		$rootScope.entity_group_name='';
		$("#entity_brand_name").val("");
		$("#entity_name").val("");
		$rootScope.search_entity_name ='';
	};
	//清除事业部品牌
	$scope.clearGroupBrand=function(){
		$rootScope.entity_brand_name = '';
		$("#entity_name").val("");
		$rootScope.search_entity_name='';
	};
	
	$scope.InitEntitys = function(input){
		if(input.entity_brand_name==''){
			$rootScope.entitys = $rootScope.map.entitys;
		}
	};
	
	$scope.LoadBrands = function(group_name){
		$rootScope.entity_group_name=group_name;
		$("#entity_brand_name").val("");
		$("#entity_name").val("");
		if(group_name==''){
			$http.get("common/groups").success(function(data) {
				//$scope.groups = data.gruops;
				$rootScope.gBrands = data.brands;
				$rootScope.entitys = data.entitys;
			});
			return;
		}
		$http.get("common/gBrands?group_name="+group_name).success(function(data) {
			$rootScope.gBrands = data;
			$rootScope.entitys = $rootScope.entitys;
		});
	};
	$scope.LoadEntitys = function(entity){
		$rootScope.entity_brand_name=entity.brand_name;
		var brand_code = entity.brand_code;
		$("#entity_name").val("");
		if(brand_code==''){
			$http.get("common/groups").success(function(data) {
				$rootScope.entitys = data.entitys;
			});
			return;
		}
		$http.get("common/entitys?brand_code="+brand_code).success(function(data) {
			$rootScope.entitys = data;
		});
	};
	$scope.LoadSeries = function(brand_code,entity_code){
        $rootScope.ch_model ="";
        $scope.models = null;
        $scope.configs = null;
        $rootScope.ch_serie="";
        if(brand_code==''){
            $scope.series = null;
			return;
		}
		if(!entity_code){
			entity_code='';
		}
		$http.get("common/series?brand_code="+brand_code+"&entity_code="+entity_code).success(function(data) {
			$rootScope.ch_serie="";
			$scope.series = data;
		});
	};

    $scope.LoadIntentConfig = function(model_code,series_code){
        $http.get("common/configs?model_code="+$scope.ch_model+"&series_code="+$scope.ch_serie).success(function(data) {
            $scope.configs = data;
        });
    };
	
	$scope.LoadModels = function(series_code,entity_code){
        $scope.models = null;
        $scope.configs = null;
        if(!entity_code){
            entity_code='';
        }
        $http.get("common/models?series_code="+series_code+"&entity_code="+entity_code).success(function(data) {
            $rootScope.ch_model ="";
            $scope.models = data;
        });
        $http.get("common/configs?series_code="+series_code+"&entity_code="+entity_code).success(function(data) {
            $scope.configs = data;
        });
	};
	$scope.logout=function(){
		if($rootScope.user.ssoLogin){
			location.href="/sys/ssoLogout";
			return;
		}
		$http.post("/logout").success(function(data) {
			if(data.code==1){
				window.top.location.href="login.html"
			}else{
				alertMsg("提示", "注销失败！");
			}
		});
	};
	 $rootScope.loadindMenu=function(obj){
		 var menuStr='<ul class="nav nav-pills nav-stacked custom-nav">';
		 $.each(obj,function(i,o){
			 var str=parseDom('<li class="menu-list"><a href="'+o.linkurl+'"><i class="fa fa-group"></i> <span>'+o.name+'</span></a></li>');
			 if(o.children){
				 concatMenu(str,o.children)
			 }
			 menuStr+=$(str).prop('outerHTML');
		 });
		 if($rootScope.user.superAdmin){
		 }
		 menuStr+="</ul>";
		 $(".left-side-inner").html(menuStr);
		 
		 var dependencies = ['js/scripts.js'];
			$script(dependencies, function() {
				$rootScope.$apply(function() {
				});
			});
	 };
	 $scope.delFlag=function(url){	 
		 var to_url=url;
		 function func1(){
			 $.ajax({
				type : "post",
				url : "entity/delFlag",
				cache : false,
				data:{id:$routeParams.id},
				async : false,
				dataType : "json",
				success : function(data) {
					$rootScope.user.flags=data;
					window.location="/#"+to_url;	 
				}
			});	 
		 }
		 
		 function func2(){
			return;
		 }
		 showconfirm("是否确认删除?",func1,func2)
		 
		/* if(confirm("是否确认删除?")){
			$.ajax({
				type : "post",
				url : "entity/delFlag",
				cache : false,
				data:{id:$routeParams.id},
				async : false,
				dataType : "json",
				success : function(data) {
					$rootScope.user.flags=data;
					$location.url(url);
				}
			});
		 }*/
	};
	 $scope.addFlag=function(url){
		 
		 	var postData={};
			var params = AppUtil.Params(".form_params");
			// 当有查询参数时,重置页数
			postData.params = JSON.stringify(params);
			
			
			var search_opt = [];
			angular.element(".option_check_list span.active").each(function(i, n) {
				var query = {};
				var _this = $(n);
				query.li_id=_this.attr("li_id");
				query.title=_this.attr("data-original-title");
				query.content=_this.attr("data-content");
				query.option=table_th[query.li_id].option;
				search_opt.push(query);
			});
			
			postData.search_opt = JSON.stringify(search_opt);
			
			
			//var flag = prompt("添加收藏,输入名称:",$(".breadcrumb .active").html());
			
			var msg="请输入收藏名称";
			var title="添加收藏";
			function func3(){
					
					var prompt_val=$.trim($("#showConfirm_input input[name='prompt_val']").val()); 
					if(prompt_val==""){
						$(".error_msg").html("提示:请输入收藏名称！").show();	
					}
					else{
						postData.flag = prompt_val;
						postData.url = url;
						$http.post("entity/addFlag",postData).success(function(data) {
							$rootScope.user.flags=data;
							$(".error_msg").html("操作提示：收藏成功！");
							$("#showConfirm_input input[name='prompt_val']").prop("disabled",true);
							$("#showConfirm_input .modal-footer").html('<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>');
							 
						}).error(function(data){ 
							$("showConfirm_input").attr("post_val","false");
							$(".error_msg").html("操作提示:收藏失败！").show();
							setTimeout(function(){$(".error_msg").html("").hide();},5000);
						});	
					}
					 
			}
			function func4(){
				return;
			}
			
			showconfirm_input(title,msg,func3,func4);
			$("#showConfirm_input input[name='prompt_val']").val($(".breadcrumb .active").html());
			
			
		
		};
	
	//修改密码	
	$scope.updatepas = function () {
        var flag = ValidF.valid({sel: ".pwd_params", msgDiv: "#pwd_msg", id: "#updatePwdForm"});
        if (!flag)return;
        var postData = AppUtil.Params(".pwd_params");
        if (null == postData.new_password || null == postData.con_password || null == postData.old_password) {
            ValidF.alert("密码不能为空.");
            return;
        }

        if (postData.new_password != postData.con_password) {
            ValidF.alert("两次输入的密码不一致.");
            return;
        }
        if (postData.new_password == postData.old_password) {
            ValidF.alert("新密码不能与原密码相同.");
            return;
        }
        delete postData.con_password;
        
        $http.post("/entity/updatePaw", postData).success(function (response) {
            if (response.code == "000") {
                $("#editPwdModal").modal("hide");
                $("#updatePwdForm")[0].reset();
                alertMsg("提示", "密码修改成功.");
            } else if (response.code == "001") {
                alertMsg("提示", "原密码输入错误！");
            } else if (response.code == "002") {
                ValidF.alert("密码不能为空.");
            } else if (response.code == "003") {

                ValidF.alert("新密码与原密码不能相同.");
            } else {
            	 $("#pwd_msg .msg").text(response.message);
                 $("#pwd_msg").fadeIn();
                 setTimeout(function () {
                     $("#pwd_msg").fadeOut();
                 }, 3000);
            }
        })

        
    };	
    
    $rootScope.clearData = function () {
        $("input[type=reset]").trigger("click");

    };
	
});
app.filter("mobile",function(){
    return function(input){
    	if(input==undefined)return "";
        return input.replace(/(\d{3})(\d{4})(\d{4})/,"$1****$3");
    		
    }
});

app.filter("idcard",function(){
    return function(input){
    	if(input==undefined)return "";
    	if(input.indexOf("x") != -1 || input.indexOf("X")!=-1){
    		return input.replace(/(\d{6})(\d{11})([x|X])/,"$1************");
    	}else{
    		return input.replace(/(\d{6})(\d{12})/,"$1************");
    	}
    }
});


app.filter("num3To2",function(){
    return function(input){
    	if(input==undefined)return "";
    	return parseFloat(input.toFixed(3)).toFixed(2);
    }
});

Number.prototype.toFixed=function(len)
{
	var add = 0;
	var s,temp;
	var s1 = this + "";
	var start = s1.indexOf(".");
	if(s1.substr(start+len+1,1)>=5)add=1;
	var temp = Math.pow(10,len);
	s = Math.floor(this * temp) + add;
	return s/temp;
};

app.run(function($rootScope, $http, AppUtil,$location) {
	AppUtil.LoadSessionUser();
	$rootScope.$on('$routeChangeSuccess', function() {
		AppUtil.ChangeMenu($location.$$path);
	});
	
});
